package com.ruoyi.product.service.impl;

import com.ruoyi.common.utils.SpecGroupUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.product.domain.ProductImage;
import com.ruoyi.product.domain.ProductSku;
import com.ruoyi.product.domain.ProductSkuSpecValue;
import com.ruoyi.product.domain.ProductSkuVo;
import com.ruoyi.product.domain.dto.SkUCouponDto;
import com.ruoyi.product.domain.request.ListUnrelatedSkuByActivityReq;
import com.ruoyi.product.mapper.ProductSkuMapper;
import com.ruoyi.product.service.IProductImageService;
import com.ruoyi.product.service.IProductSkuService;
import com.ruoyi.product.service.IProductSkuSpecValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 商品SKUService业务层处理
 *
 * @author liuhuizhong
 * @date 2025-07-11
 */
@Service
public class ProductSkuServiceImpl implements IProductSkuService {
    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private IProductImageService productImageService;
    @Autowired
    private IProductSkuSpecValueService productSkuSpecValueService;

    /**
     * 查询商品SKU（包含图片列表）
     *
     * @param id 商品SKU主键
     * @return 商品SKU
     */
    @Override
    public ProductSkuVo selectProductSkuById(Long id) {
        ProductSkuVo productSku = productSkuMapper.selectProductSkuById(id);
        if (productSku != null) {
            // 查询并设置关联图片列表
            List<ProductImage> images = productImageService.selectProductImageList(new ProductImage() {
                @Override
                public Long getSkuId() {
                    return productSku.getId();
                }
            });
            productSku.setProductImages(images);
            List<ProductSkuSpecValue> specValues = productSkuSpecValueService
                    .selectProductSkuSpecValueList(new ProductSkuSpecValue() {
                        @Override
                        public Long getSkuId() {
                            return productSku.getId();
                        }
                    });
            productSku.setSpecValues(specValues);

        }
        return productSku;
    }

    /**
     * 查询商品SKU
     *
     * @param id 商品SKU主键
     * @return 商品SKU
     */
    @Override
    public List<ProductSkuVo> selectProductSkuById1(Long id) {
        List<ProductSkuVo> productSkuVo = productSkuMapper.selectProductSkuById1(id);

        LinkedHashMap<Long, ProductSkuVo> mergedMap = new LinkedHashMap<>();
        for (ProductSkuVo item : productSkuVo) {
            Long id1 = item.getId();

            ProductSkuVo vo = mergedMap.get(id1);
            if (vo == null) {
                ProductSkuVo vo1 = new ProductSkuVo();
                vo1.setId(item.getId());
                vo1.setSpuId(item.getSpuId());
                vo1.setCode(item.getCode());
                vo1.setCategoryId(item.getCategoryId());
                vo1.setSkuName(item.getSkuName());
                vo1.setDescription(item.getDescription());
                vo1.setPrice(item.getPrice());
                vo1.setOriginalPrice(item.getOriginalPrice());
                vo1.setStock(item.getStock());
                vo1.setLowStock(item.getLowStock());
                vo1.setWeight(item.getWeight());
                vo1.setVolume(item.getVolume());
                vo1.setStatus(item.getStatus());
                vo1.setCreatedAt(item.getCreatedAt());
                vo1.setUpdatedAt(item.getUpdatedAt());
                vo1.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(item.getSpecNameGroupRaw()));
                vo1.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(item.getSpecValueGroupRaw()));
                vo1.setUrl(item.getUrl());
                vo1.setUrls(new ArrayList<>());
                // 处理urL字段
                if (item.getUrl() != null && !item.getUrl().isEmpty()) {
                    vo1.getUrls().add(item.getUrl());
                }
                mergedMap.put(id1, vo1);

            } else {
                if (item.getUrl() != null && !item.getUrl().isEmpty()) {
                    // vo.getUrls().add(item.getUrl());
                    if (!vo.getUrls().contains(item.getUrl())) {
                        vo.getUrls().add(item.getUrl());
                    }
                }
            }
        }

        return new ArrayList<>(mergedMap.values());
    }

    /**
     * 查询商品SKU列表（包含图片列表）
     *
     * @param productSku 商品SKU
     * @return 商品SKU
     */
    @Override
    public List<ProductSku> selectProductSkuList(ProductSku productSku) {
        List<ProductSku> skuList = productSkuMapper.selectProductSkuList(productSku);
        // 为每个SKU设置图片列表
        for (ProductSku sku : skuList) {
            List<ProductImage> images = productImageService.selectProductImageList(new ProductImage() {
                @Override
                public Long getSkuId() {
                    return sku.getId();
                }
            });
            sku.setProductImages(images);
        }
        return skuList;
    }

    @Override
    public List<ProductSku> selectUnrelatedSkuByActivity(ListUnrelatedSkuByActivityReq req) {
        List<ProductSku> skus = productSkuMapper.selectUnrelatedSkuByActivity(req);
        for (ProductSku sku : skus) {
            List<ProductImage> images = productImageService.selectProductImageList(new ProductImage() {
                @Override
                public Long getSkuId() {
                    return sku.getId();
                }
            });
            sku.setProductImages(images);
        }
        return skus;
    }

    /**
     * 新增商品SKU
     *
     * @param productSku 商品SKU
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertProductSku(ProductSku productSku) {
        // 1. 先保存SKU信息，获取自动生成的ID
        int result = productSkuMapper.insertProductSku(productSku);
        if (result <= 0) {
            return result;
        }

        // 2. 处理图片列表（绑定当前SKU的ID）
        handleProductImages(productSku, productSku.getProductImages());
        handleProductSkuSpecValue(productSku);

        return result;
    }

    private void handleProductSkuSpecValue(ProductSku productSku) {
        if (!StringUtils.isEmpty(productSku.getSpecValues())) {
            for (ProductSkuSpecValue specValue : productSku.getSpecValues()) {
                specValue.setSkuId(productSku.getId());
            }
            productSkuSpecValueService.insertProductSkuSpecValueBatch(productSku.getSpecValues());
        }
    }

    /**
     * 修改商品SKU
     *
     * @param productSku 商品SKU
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateProductSku(ProductSku productSku) {
        // 1. 删除原有图片
        productImageService.deleteProductImageBySkuId(productSku.getId());
        // 2. 处理新图片列表
        handleProductImages(productSku, productSku.getProductImages());
        // 3. 删除原有属性
        productSkuSpecValueService.deleteProductSkuSpecValueBySkuId(productSku.getId());
        // 4. 处理属性列表
        handleProductSkuSpecValue(productSku);

        // 5. 更新SKU信息
        return productSkuMapper.updateProductSku(productSku);
    }

    /**
     * 批量删除商品SKU
     *
     * @param ids 需要删除的商品SKU主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProductSkuByIds(Long[] ids) {
        // 先删除所有关联的图片
        for (Long id : ids) {
            productImageService.deleteProductImageBySkuId(id);
        }
        // 再删除SKU本身
        return productSkuMapper.deleteProductSkuByIds(ids);
    }

    /**
     * 删除商品SKU信息
     *
     * @param id 商品SKU主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProductSkuById(Long id) {
        // 先删除关联的图片
        productImageService.deleteProductImageBySkuId(id);
        // 再删除SKU本身
        return productSkuMapper.deleteProductSkuById(id);
    }

    /**
     * 处理商品SKU的图片信息
     *
     * @param productSku 商品SKU对象
     * @param images     图片列表
     */
    private void handleProductImages(ProductSku productSku, List<ProductImage> images) {
        // 校验图片列表是否为空
        if (StringUtils.isEmpty(images)) {
            return;
        }

        // 为每张图片绑定当前SKU的ID，并过滤无效数据
        for (ProductImage image : images) {
            // 跳过空对象或URL为空的无效图片
            if (image == null || StringUtils.isBlank(image.getUrl())) {
                continue;
            }
            // 强制绑定当前SKU的ID，确保关联正确
            image.setSkuId(productSku.getId());
            image.setSpuId(productSku.getSpuId());
            image.setSort(image.getSort() == null ? 0L : image.getSort());
            // 处理URL前后空格
            image.setUrl(image.getUrl().trim());
        }

        // 批量插入有效图片
        productImageService.insertBatchProductImage(images);
    }

    /**
     * 获取SKU优惠券信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<SkUCouponDto> getSkuCoupon(Long userId, Long skuId) {
        List<SkUCouponDto> skuCouponDto = productSkuMapper.getSkuCoupon(userId, skuId);
        return skuCouponDto;
    }
}
